package com.ruoyi.common.security.aspect;

import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.reflect.ReflectUtils;
import com.ruoyi.common.security.annotation.DefaultCreateProperty;
import com.ruoyi.common.security.annotation.DefaultUpdateProperty;
import com.ruoyi.common.security.annotation.EnterpriseAndApplicationCodeProperty;
import com.ruoyi.common.security.utils.SecurityUtils;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.ModelAndViewContainer;

public class RequestDefaultPropertyMethodArgumentResolver   extends BaseEntityModelAttributeMethodProcessor {

    public RequestDefaultPropertyMethodArgumentResolver(boolean annotationNotRequired) {
        super(annotationNotRequired);
    }


    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        //System.out.println("enter supportsParameter");
        return parameter.hasParameterAnnotation(DefaultCreateProperty.class)||
                parameter.hasParameterAnnotation(DefaultUpdateProperty.class)||
                parameter.hasParameterAnnotation(EnterpriseAndApplicationCodeProperty.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        System.out.println("enter resolveArgument");
        Object p = super.resolveArgument(parameter, mavContainer, webRequest, binderFactory);
        // 处理 DefaultCreateProperty 注解
        if (parameter.hasParameterAnnotation(DefaultCreateProperty.class)) {
            ReflectUtils.setFieldValue(p, "createBy", SecurityUtils.getUsername());
            ReflectUtils.setFieldValue(p, "createTime", DateUtils.getNowDate());
        }

        // 处理 DefaultUpdateProperty 注解
        if (parameter.hasParameterAnnotation(DefaultUpdateProperty.class)) {
            ReflectUtils.setFieldValue(p, "updateBy", SecurityUtils.getUsername());
            ReflectUtils.setFieldValue(p, "updateTime", DateUtils.getNowDate());
        }

        // 处理 EnterpriseAndApplicationCodeProperty 注解
        if (parameter.hasParameterAnnotation(EnterpriseAndApplicationCodeProperty.class)) {
            ReflectUtils.setFieldValue(p, "enterpriseCode", SecurityUtils.getEnterpriseCode());
            if (ReflectUtils.getAccessibleField(p, "applicationCode") != null) {
                ReflectUtils.setFieldValue(p, "applicationCode", SecurityUtils.getApplicationCode());
            }
        }
        return p;
    }



}
